# -*-coding=utf-8 -*-
from sklearn.feature_extraction import DictVectorizer
import csv
import math
import operator
from sklearn import preprocessing
from sklearn import tree
from sklearn.externals.six import StringIO
import random

def euclideanDistance(instance1, instance2, length):
	distance = 0
	for x in range(length):
		distance += pow((float(instance1[x])-float(instance2[x])), 2)
	return math.sqrt(distance)

def getNeighbors(trainingSet, testInstance, k):
	distances = []
	length = len(testInstance)-1
	for x in range(len(trainingSet)):
		dist = euclideanDistance(testInstance, trainingSet[x], length)
		distances.append((trainingSet[x], dist))
	distances.sort(key=operator.itemgetter(1))
	neighbors = []
	for x in range(k):
		neighbors.append(distances[x][0])
	return neighbors

def getResponse(neighbors):
	classVotes = {}
	for x in range(len(neighbors)):
		response = neighbors[x][-1]
		if response in classVotes:
			classVotes[response] += 1
		else:
			classVotes[response] = 1
		sortedVotes = sorted(classVotes.iteritems(), key=operator.itemgetter(1), reverse=True)
		return sortedVotes[0][0]

def getAccuracy(testSet, predictions):
	correct = 0
	for x in range(len(testSet)):
		if testSet[x][-1] == predictions[x]:
			correct += 1
	return (correct/float(len(testSet))) * 100.0

def main():
	#Read in the csv file and put features in a list of dict and list of class label.
	allElectronicsData = open(r'datasets/KnnMovie.csv', 'rU')
	reader = csv.reader(allElectronicsData)
	headers = reader.next()

	print headers

	trainingSet = []
	testSet = []
	split = 0.5

	for row in reader:
		rowDict = []
		for i in range(1, len(row)):
			# print row[i]
			rowDict.append(row[i])
			# print "rowDict:", rowDict

		if random.random()<split:
			trainingSet.append(rowDict)
		else:
			testSet.append(rowDict)

	# print featureList

	# generate predictions
	predictions = []
	k = 2
	for x in range(len(testSet)):
		neighbors = getNeighbors(trainingSet, testSet[x], k)
		result = getResponse(neighbors)
		predictions.append(result)
		print "> predicted="+repr(result)+", actual="+repr(testSet[x][-1])
	accuracy = getAccuracy(testSet, predictions)
	print 'Accuracy'+repr(accuracy)+'%'

	# neighbors = getNeighbors(trainingSet, [9,106,'Titanic'], k)
	# result = getResponse(neighbors)
	# predictions.append(result)
	# print "> predicted="+repr(result)+", actual=Romance"

main()